<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="600px"
    @close="close"
  >
    <el-form ref="formRef" label-width="200px" :model="form" :rules="rules">
      <el-form-item label="上传文件" prop="TrackPic">
        <el-upload
          v-model:file-list="TrackPic"
          :disabled="flag"
          :multiple="true"
          class="avatar-uploader"
          action="https://api.sanjianke.com/common/Upload/upload?file=Customer/Trackpic&type=image"
          list-type="picture-card"
        >
          <!-- :disabled="!isUpOrderAttach" -->
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div style="height: 100%; width: 100%">
              <img
                v-if="isImage(file) == true"
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <div
                v-else
                style="
                  height: 100%;
                  width: 100%;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <div style="font-size: 25px">
                  {{ isImage(file) }}
                </div>
              </div>
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="统计月份" prop="CountMonth">
        <el-date-picker
          v-model="form.CountMonth"
          :disabled="flag"
          type="month"
          placeholder="请选择月份"
          :size="size"
        />
      </el-form-item>
      <el-form-item label="是否达标行业优选商家" prop="isGoodStore">
        <el-select
          v-model="form.isGoodStore"
          :disabled="flag"
          style="width: 220px"
          placeholder=""
        >
          <el-option :value="1" label="是" />
          <el-option :value="0" label="否" />
        </el-select>
      </el-form-item>
      <el-form-item label="金冠商品数" prop="JinguanProductNum">
        <el-input-number
          v-model="form.JinguanProductNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="上月在线商品数" prop="upMonthProductNum">
        <el-input-number
          v-model="form.upMonthProductNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="展现次数" prop="ShowNum">
        <el-input-number
          v-model="form.ShowNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="访客数" prop="FangkeNum">
        <el-input-number
          v-model="form.FangkeNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="浏览量" prop="LiulanNum">
        <el-input-number
          v-model="form.LiulanNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="询盘量" prop="XunpanNum">
        <el-input-number
          v-model="form.XunpanNum"
          :disabled="flag"
          :min="0"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="form.TrackMemo"
          :disabled="flag"
          :rows="2"
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible">
      <img
        w-full
        :src="dialogImageUrl"
        style="width: 100%"
        alt="Preview Image"
      />
    </el-dialog>
    <template v-if="!flag" #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/customerTrackingTracklist'

  export default defineComponent({
    name: 'StoreEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        dialogImageUrl: '',
        dialogVisible: false,
        flag: false,
        TrackPic: [],
        formRef: null,
        form: {},
        rules: {
          TrackPic: [
            { required: true, trigger: 'blur', message: '请上传相关截图' },
          ],
          CountMonth: [
            { required: true, trigger: 'change', message: '请选择月份' },
          ],
          isGoodStore: [
            { required: true, trigger: 'change', message: '请选择是否达标' },
          ],
          JinguanProductNum: [
            { required: true, trigger: 'blur', message: '请输入金冠商品数' },
          ],
          upMonthProductNum: [
            { required: true, trigger: 'blur', message: '请输入上月在线品数' },
          ],
          ShowNum: [
            { required: true, trigger: 'blur', message: '请输入展示次数' },
          ],
          FangkeNum: [
            { required: true, trigger: 'blur', message: '请输入访客数量' },
          ],
          LiulanNum: [
            { required: true, trigger: 'blur', message: '请输入浏览量' },
          ],
          XunpanNum: [
            { required: true, trigger: 'blur', message: '请输入询盘量' },
          ],
        },
        edittype: 0,
        title: '',
        dialogFormVisible: false,
      })

      const showEdit = (row, flag) => {
        if (flag == 'look') {
          state.flag = true
        } else {
          state.flag = false
        }
        if (row == 0) {
          row = {
            TrackClass: 0,
            TrackType: 1,
            TrackID: 0,
          }
        }
        state.title = '店铺后台数据'
        state.form = Object.assign({}, row)
        if (!row.TrackMemo) {
          state.form.TrackMemo = ''
        }
        if (row.TrackPic) {
          state.TrackPic = row.TrackPic
        }
        state.dialogFormVisible = true
      }

      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          roles: [],
        }
        state.TrackPic = []
        state.dialogFormVisible = false
      }
      const save = () => {
        console.log(state.TrackPic, 'state.form')
        const TrackPic = []

        state.TrackPic.forEach((item) => {
          if (item.response) {
            TrackPic.push({
              // name: item.name,
              url: item.response.data.url,
            })
          } else {
            TrackPic.push({
              // name: item.name,
              url: item.url,
            })
          }
        })
        state.form.TrackPic = TrackPic

        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const handlePictureCardPreview = (uploadFile) => {
        console.log('uploadFile', uploadFile)
        // 判断是否是临时地址
        if (uploadFile.raw) {
          const isType = uploadFile.raw.type.split('/')[0]
          if (isType == 'image') {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        } else {
          if (
            splitLastDot(uploadFile.url) == 'png' ||
            splitLastDot(uploadFile.url) == 'jpg' ||
            splitLastDot(uploadFile.url) == 'jpge'
          ) {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
          } else {
            window.open(uploadFile.url, '_blank')
          }
        }
      }

      // 是否是图片
      const isImage = (row) => {
        console.log(row, '搞不懂')

        if (row.raw) {
          // 临时地址
          const isType = row.raw.type.split('/')[0]
          const isTypeName = row.name.split('.')[1]
          if (isType == 'image') {
            return true
          } else {
            return isTypeName
          }
        } else {
          // 线上地址
          if (
            splitLastDot(row.url) == 'png' ||
            splitLastDot(row.url) == 'jpg' ||
            splitLastDot(row.url) == 'jpge'
          ) {
            return true
          } else {
            return splitLastDot(row.url)
          }
        }
      }
      // 反转字符串
      const splitLastDot = (msg) => {
        // 首先反转字符串
        const reversedStr = msg.split('').reverse().join('')
        // 使用split切割第一个点
        const parts = reversedStr.split('.')[0]
        // 结果反转并返回
        return parts.split('').reverse().join('')
      }

      const handleRemove = (row) => {
        if (state.flag) {
          return
        }
        const index = state.TrackPic.findIndex((TrackPicItem) => {
          console.log(TrackPicItem.url, row.url, '123')
          return TrackPicItem.url === row.url
        })
        state.TrackPic.splice(index, 1)
      }
      // const handleAvatarSuccess = (response) => {
      //   const data = {
      //     url: response.data.url,
      //   }
      //   state.TrackPic.push(data)
      //   state.form.TrackPic = state.TrackPic
      //   ElMessage({
      //     message: '上传成功',
      //     type: 'success',
      //   })
      // }

      return {
        ...toRefs(state),
        handleRemove,
        splitLastDot,
        handlePictureCardPreview,
        showEdit,
        isImage,
        close,
        save,
      }
    },
  })
</script>
